package com.runas.util;

import org.apache.commons.io.FileUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

	public static void main(String[] args) throws Exception {
//		byte[] zip = zip(new File("/dist/ai-raw"));
//		FileUtils.writeByteArrayToFile(new File("/dist/ai-raw.zip"),zip);
		unzip(FileUtils.readFileToByteArray(new File("/dist/ai-raw.zip")),new File("/dist/"));
	}
	
	public static byte[] zip(File dir) {
		if (dir.exists()) {
			try {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				ZipOutputStream zos = new ZipOutputStream(bos);
				doZip(zos, dir, dir.getName());
				zos.close();
				return bos.toByteArray();
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		return null;
	}

	private static void doZip(ZipOutputStream zos, File dir, String path) throws Exception {
		File[] files = dir.listFiles();
		path = path.endsWith("/") ? path : path + "/";
		for (File f : files) {
			if (f.isDirectory()) {
				doZip(zos, f, path + f.getName());
			} else {
				ZipEntry entry = new ZipEntry(path + f.getName());
				entry.setSize(f.length());
				entry.setTime(f.lastModified());
				zos.putNextEntry(entry);
				zos.write(FileUtils.readFileToByteArray(f));
				zos.closeEntry();
			}
		}
	}

	public static boolean unzip(byte[] data, File basedir) {
		try {
			if (!basedir.exists())
				basedir.mkdir();
			ByteArrayInputStream bis = new ByteArrayInputStream(data);
			ZipInputStream zis = new ZipInputStream(bis);
			ZipEntry entry = null;
			while ((entry = zis.getNextEntry()) != null) {
				String name = entry.getName();
				byte[] buf = new byte[1024];
				int read = -1;
				File target = new File(basedir, name);
				if (entry.isDirectory())
					target.mkdirs();
				else {
					if (!target.getParentFile().exists())
						target.getParentFile().mkdirs();
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					while ((read = zis.read(buf)) != -1) {
						bos.write(buf, 0, read);
					}
					bos.close();
					byte[] content = bos.toByteArray();
					FileUtils.writeByteArrayToFile(target, content);
				}
			}
			bis.close();
			zis.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return true;
	}

}
